package com.glsc.ngateway.platform.service.softLegal;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.flow.cmdb.FlowFormPartInRepo;
import com.glsc.ngateway.platform.domain.softLegal.SoftChangeLog;
import com.glsc.ngateway.platform.domain.softLegal.SoftIn;
import com.glsc.ngateway.platform.repo.softLegal.SoftChangeLogRepository;
import com.glsc.ngateway.platform.repo.softLegal.SoftInRepository;
import com.glsc.ngateway.platform.service.cmdb.SequenceProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

import static com.glsc.ngateway.common.api.common.enums.DictConstant.*;
import static com.glsc.ngateway.platform.utils.PlatformLocalConstant.SOFT_IN;

@Service
public class SoftInService {

    @Autowired
    private SequenceProductService sequenceProductService;
    @Autowired
    private SoftInRepository softInRepository;
    @Autowired
    private SoftChangeLogRepository softChangeLogRepository;
    @Autowired
    private FlowFormPartInRepo flowFormPartInRepo;

    public Object search(Object paramsObj) {
        JSONObject objParmams = JSONObject.parseObject(JSONObject.toJSONString(paramsObj)).entrySet().stream()
                .filter(entry -> !entry.getValue().toString().isEmpty())
                .collect(JSONObject::new, (obj, entry) -> obj.put(entry.getKey(), entry.getValue()), JSONObject::putAll);

        if (StrUtil.isEmpty(objParmams.getString("orderByDirection"))) {
            objParmams.put("orderByDirection", "ASC");
        }
        if (StrUtil.isEmpty(objParmams.getString("orderByField"))) {
            objParmams.put("orderByField", "id");
        }
        Sort sort = Sort.by(Sort.Direction.fromString(objParmams.getString("orderByDirection")), objParmams.getString("orderByField"));

        Pageable pageable = PageRequest.of(objParmams.getInteger("pageNo") - 1, objParmams.getInteger("pageSize"), sort);

        SoftIn paramSearchDto = JSONObject.parseObject(JSONObject.toJSONString(objParmams), SoftIn.class);
        Page<SoftIn> result = softInRepository.searchByParam(pageable, paramSearchDto);
//        result.getContent().forEach(e -> {
//            if (e.getCmdbCpuStandard() != null) {
//                e.setPartNum(e.getCmdbCpuStandard().getPartNum());
//            }
//        });
        return result;
    }

    /**
     * @param softIn
     * @param account       操作人员
     */
    public SoftIn addOrUpdate(SoftIn softIn, String account) {
        int addOrUpdateFlag = 0;
        softIn.setIsDelete(NO_DELETE);
        SoftChangeLog log = new SoftChangeLog();
        if (softIn.getId() != null) {
            // 修改
            log.setChangeType(DictConstant.UPDATE_STRING);
            addOrUpdateFlag = 2;
        } else {
            // 新增
            log.setChangeType(DictConstant.ADD_STRING);
            addOrUpdateFlag = 1;
        }
//        //校验重复
//        if (addOrUpdateFlag != 0){
//            checkUnique(softIn, addOrUpdateFlag);
//        }
        log.setChangeContent(JSONObject.toJSONString(softIn));
        log.setChangeFrom(CMDB_CPU_DETAIL);
        log.setChangeId(softIn.getId() != null ? softIn.getId().toString() : null);
        log.setChangeUser(account);
        softChangeLogRepository.save(log);
        softInRepository.save(softIn);
        return softIn;
    }

    private void checkUnique(SoftIn softIn, int addOrUpdateFlag) {
        if (StrUtil.isNotEmpty(softIn.getSoftwareName())) {
            if (addOrUpdateFlag == 1) {
                findSame(softIn);
            } else {
                //修改情况，要把已有结果查询出来，如果有变化还要校验
                Optional<SoftIn> result = softInRepository.findById(softIn.getId());
                if (result.isPresent()) {
                    if (result.get().getSoftwareName() != null && !result.get().getSoftwareName().equals(softIn.getSoftwareName())) {
                        if (result.get().getIsDelete().equals(NO_DELETE)) {
                            findSame(softIn);
                        }
                    }
                    //修改情况存在未删除的记录
                } else {
                    findSame(softIn);
                }
            }

        }
    }

    public void findSame(SoftIn softIn) {
        List<SoftIn> result = softInRepository.findAllBySoftwareNameAndIsDelete(softIn.getSoftwareName(), NO_DELETE);
        if (CollectionUtil.isNotEmpty(result)) {
            throw PlatformException.errorWithOutMail("名称重复");
        }
//        if (!StrUtil.equals(CMDB_CONFIRM,cmdbConfirm)){
//            List<FlowFormPartIn> flowFormPartInDetails = flowFormPartInRepo.findFlowCpuSn(softIn.getSn());
//            if (CollectionUtil.isNotEmpty(flowFormPartInDetails)){
//                throw PlatformException.errorWithOutMail("有发起过的流程"+flowFormPartInDetails.get(0).getProcessTitle()+"存在相同的cpu序列号");
//            }
//        }

    }

    public void delete(SoftIn softIn, String account) {
        SoftChangeLog log = new SoftChangeLog();
        log.setChangeContent(JSONObject.toJSONString(softIn));
        log.setChangeFrom(SOFT_IN);
        log.setChangeId(softIn.getId().toString());
        log.setChangeUser(account);
        log.setChangeType(DELETE_STRING);
        Optional<SoftIn> optional = softInRepository.findById(softIn.getId());
        if (optional.isPresent()) {
            SoftIn bean = optional.get();
            bean.setIsDelete(DELETED);
            softInRepository.save(bean);
            softChangeLogRepository.save(log);
        } else {
            throw PlatformException.errorWithOutMail("删除记录不存在");
        }
    }

//    public void deleteByCodeList(List<String> codes, String account) {
//        SoftChangeLog log = new SoftChangeLog();
//        log.setChangeContent(JSONObject.toJSONString(codes));
//        log.setChangeFrom(CMDB_CPU_DETAIL);
//        log.setChangeUser(account);
//        log.setChangeType(DELETE_BATCH_STRING);
//        softChangeLogRepository.save(log);
//        softInRepository.updateIsDeleteByCodes(DELETED, codes);
//    }

//    public void deleteByDeviceDetailId(Integer deviceDetailId, String operator) {
//        SoftChangeLog log = new SoftChangeLog();
//        log.setChangeContent(JSONObject.toJSONString(deviceDetailId));
//        log.setChangeFrom(CMDB_DEVICE_DETAIL);
//        log.setChangeUser(operator);
//        log.setChangeType(DELETE_BATCH_STRING);
//        softChangeLogRepository.save(log);
//        softInRepository.updateIsDeleteByDeviceDetailId(DELETED, deviceDetailId);
//    }

//    public void outByDeviceDetail(CmdbDeviceDetail h, String operator) {
//        List<SoftIn> cpuDetails = softInRepository.findAllByDeviceCodeAndIsDelete(h.getDeviceDetailCode(), NO_DELETED);
//        cpuDetails.stream().forEach(e -> e.setLifeStatus(PART_LIFE_CYCLE_OUT));
//        softInRepository.saveAll(cpuDetails);
//        SoftChangeLog log = new SoftChangeLog();
//        log.setChangeContent(JSONObject.toJSONString(h.getDeviceDetailId()));
//        log.setChangeFrom(CMDB_DEVICE_DETAIL);
//        log.setChangeUser(operator);
//        log.setChangeType(UPDATE_STRING);
//        softChangeLogRepository.save(log);
//    }

//    public void outBySn(String sn, String operator) {
//        List<SoftIn> cpuDetails = softInRepository.findAllBySnAndIsDelete(sn, NO_DELETE);
//        SoftIn cpuDetail = cpuDetails.get(0);
//        cpuDetail.setLifeStatus(PART_LIFE_CYCLE_OUT);
//        softInRepository.save(cpuDetail);
//        SoftChangeLog log = new SoftChangeLog();
//        log.setChangeContent(JSONObject.toJSONString(sn));
//        log.setChangeFrom(CMDB_CPU_DETAIL);
//        log.setChangeUser(operator);
//        log.setChangeType(UPDATE_STRING);
//        softChangeLogRepository.save(log);
//    }

//    /**
//     * 根据序列号查询
//     * @param snList
//     * @return
//     */
//    public List<SoftIn> listBySn(List<String> snList) {
//        Map<String, Object> param = new HashMap<>();
//        param.put("INSTR_sn", StringUtils.join(snList,","));
//        param.put("EQ_isDelete", 0);
//
//        List<SoftIn> detailLis = softInRepository.findAll(SpecificationUtil.buildSpecification(param, SoftIn.class));
//        return detailLis;
//    }
//
//    public List<SoftIn> listByDetailCode(List<String> collect) {
//        return softInRepository.findAllByCpuDetailCodeIn(collect);
//    }
}
